﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyChannel.Resources;
using MyChannel.Library;
using MyChannel.Category;
using MyChannel.Home;
using Microsoft.Phone.Tasks;
using MyChannel.LinqSupport;
using Coding4Fun.Toolkit.Controls;
using MyChannel.DownloadComponent;
using System.Windows.Threading;
using Microsoft.Phone.Info;

namespace MyChannel
{
    public partial class MainPage : PhoneApplicationPage
    {
        MD5 md5 = new MD5();
        ListCategory listCategory;
        ListHome listHome;
        bool isloadcategory = false;
        bool isloadhome = false;
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        private string strConnectionString = @"isostore:/FavoriteDB.sdf";

        public MainPage()
        {
            InitializeComponent();
            GetDeviceInfo();
            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Start();
        }

        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine((DeviceStatus.ApplicationCurrentMemoryUsage / 1048576) + "MB");
        }

        private void GetDeviceInfo()
        {
            App.DeviceID = md5.GetMD5(Windows.Phone.System.Analytics.HostInformation.PublisherHostId);
            App.OsVersion = System.Environment.OSVersion.Version.Major.ToString();
            App.DeviceName = Microsoft.Phone.Info.DeviceStatus.DeviceName.ToString();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            List_Category.SelectedIndex = -1;
            List_Home.SelectedIndex = -1;
            List_Favorite.SelectedIndex = -1;
            List_Downloaded.SelectedIndex = -1;
            ItemDownloading.SelectedIndex = -1;
            Layout_network_error.Visibility = System.Windows.Visibility.Collapsed;
            Layout_Progress_Cate.Visibility = System.Windows.Visibility.Collapsed;
            Layout_Progress_Home.Visibility = System.Windows.Visibility.Collapsed;
            LoadData(0);
            base.OnNavigatedTo(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Do you want exit ?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                App.Current.Terminate();
            }
            else
            {
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }


        private void LoadData(int i)
        {
            switch(i)
            {
                case 1:
                    {
                        if (!isloadcategory)
                        {
                            Layout_network_error.Visibility = System.Windows.Visibility.Visible;
                            Layout_Progress_Cate.Visibility = System.Windows.Visibility.Visible;
                            listCategory = new ListCategory();
                            List_Category.DataContext = listCategory;
                            ProgressCate.DataContext = listCategory;
                            network_error.DataContext = listCategory;
                            
                            isloadcategory = true;
                        }

                    }break;
                case 0:
                    {
                        if (!isloadhome)
                        {
                            Layout_network_error.Visibility = System.Windows.Visibility.Visible;
                            Layout_Progress_Home.Visibility = System.Windows.Visibility.Visible;
                            listHome = new ListHome();
                            List_Home.DataContext = listHome;
                            ProgressHome.DataContext = listHome;
                            network_error.DataContext = listHome;
                            isloadhome = true;
                        }
                    }break;
                case 2:
                    {
                        IList<DataFavorite> listData = null;
                            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
                            {
                                
                                IQueryable<DataFavorite> dataQuery = from data in readAndWrite.TableFavorite select data;
                                listData = dataQuery.ToList();
                            }
                            List_Favorite.DataContext = listData;

                    }break;
                case 3:
                    {
                        List<LocalVideo> localvideo= null;
                        List<DownObject> listlocal = new List<DownObject>();
                        LocalPlaylist local = App.ViewModel.PlaylistList[0];
                        localvideo = (from video in local.Videos where video.State == "Completed" select video).ToList();
                        for (int a = 0; a < localvideo.Count; a++)
                        {
                            listlocal.Add(new DownObject
                            {
                                D_Name = localvideo[a].Name,
                                D_Image = localvideo[a].Img,
                                D_Link = App.DIRECTORY_SAVE_DOWNLOAD+localvideo[a].Name
                            });

                        }
                        List_Downloaded.DataContext = listlocal;
                    }break;
            }

        }

        private void Reload_Click(object sender, RoutedEventArgs e)
        {
            isloadhome = false;
            isloadcategory = false;
            LoadData(Mainpivot.SelectedIndex);
        }

        private void Mainpivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GC.Collect();
            LoadData(Mainpivot.SelectedIndex);
        }

        private void List_Home_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Home.SelectedIndex < 0)
                return;
            App.URL = (List_Home.SelectedItem as HomeObject).Link;
            int type = int.Parse((List_Home.SelectedItem as HomeObject).Type);
           switch(type)
           {
               case 0:
                   {
                       NavigationService.Navigate(new Uri("/ViewVideoPage.xaml?type=online", UriKind.Relative));
                   }break;
               case 1:
                   {

                   }break;
               default: break;
           }
            
        }

        private void List_Category_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Category.SelectedIndex < 0)
                return;
            string CategoryName = (List_Category.SelectedItem as CategoryObject).Name;
            CategoryName = CategoryName.Replace("&","%26");
            App.CategoryAction = (List_Category.SelectedItem as CategoryObject).Action;
            bool haveImage = (List_Category.SelectedItem as CategoryObject).ImageVideo;
            if(haveImage)
                NavigationService.Navigate(new Uri("/CategoryDetailPage.xaml?name=" + CategoryName, UriKind.Relative));
            else
                NavigationService.Navigate(new Uri("/CategoryDetailPage2.xaml?name=" + CategoryName, UriKind.Relative));
          
        }
        #region aplication bar
        private void Rate_Click(object sender, EventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }
        private void App_bar_StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            var appBar = sender as ApplicationBar;
            if (appBar == null) return;
            appBar.Opacity = e.IsMenuVisible ? 1 : 0.5;
        }
        private void appbar_contact_Click(object sender, EventArgs e)
        {
            EmailComposeTask emailComposeTask = new EmailComposeTask();
            emailComposeTask.Subject = "[CARTOON HD - Windowsphone 8] - APP VERSION: 1.0.0";
            emailComposeTask.Body = "";
            emailComposeTask.To = "lamnt@nct.vn";
            emailComposeTask.Bcc = "";
            emailComposeTask.Show();
        }
        private void appbar_request_Click(object sender, EventArgs e)
        {
            EmailComposeTask emailComposeTask = new EmailComposeTask();
            emailComposeTask.Subject = "[APP NAME - Windowsphone 8] - REQUEST MOVIE";
            emailComposeTask.Body = "";
            emailComposeTask.To = "lamnt@nct.vn";
            emailComposeTask.Bcc = "";
            emailComposeTask.Show();
        }
        private void appbar_share_Click(object sender, EventArgs e)
        {
            ShareLinkTask shareLinkTask = new ShareLinkTask();
            shareLinkTask.Title = "Cartoon HD";
            shareLinkTask.LinkUri = new Uri("link app", UriKind.Absolute);
            shareLinkTask.Message = "The best app for cartoon movie !";
            shareLinkTask.Show();
        }
        private void appbar_more_Click(object sender, EventArgs e)
        {
            MarketplaceSearchTask marketplaceSearchTask = new MarketplaceSearchTask();

            marketplaceSearchTask.SearchTerms = "PhucVo";

            marketplaceSearchTask.Show();
        }
        #endregion

        #region add favorite category
        CategoryObject tempCategoryObject;
        private void category_item_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            tempCategoryObject = (sender as Grid).DataContext as CategoryObject;

            Grid item = sender as Grid;

            ContextMenu contextMenu = new ContextMenu();
            MenuItem addFavorite = new MenuItem();
            addFavorite.Header = "Add to favorite";
            addFavorite.Click += addFavorite_Click;

            contextMenu.Items.Add(addFavorite);
            ContextMenuService.SetContextMenu(item, contextMenu);
            contextMenu.IsOpen = true;
        }

        void addFavorite_Click(object sender, RoutedEventArgs e)
        {
            IList<DataFavorite> listData = null;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataFavorite> dataQuery = from data in readAndWriteDB.TableFavorite where data.name.Equals(tempCategoryObject.Name) && data.image.Equals(tempCategoryObject.Image) select data;
                listData = dataQuery.ToList();
                if (listData.Count > 0)
                {
                    var toast = GetToastWithImgAndTitle(tempCategoryObject.Name+App.message_exist, "");
                    toast.TextWrapping = TextWrapping.Wrap;
                    toast.Show();
                }
                else
                {
                    DataFavorite newsdata = new DataFavorite
                    {
                        ID = DateTime.Now.ToString(),
                        style = "1",
                        name = tempCategoryObject.Name,
                        type = tempCategoryObject.Type,
                        link = "",
                        image = tempCategoryObject.Image,
                        action = tempCategoryObject.Action,
                        imagevideo = tempCategoryObject.ImageVideo ? "1" : "0"
                    };
                    readAndWriteDB.TableFavorite.InsertOnSubmit(newsdata);
                    readAndWriteDB.SubmitChanges();
                    var toast = GetToastWithImgAndTitle(tempCategoryObject.Name + App.message_added, "");
                    toast.TextWrapping = TextWrapping.Wrap;
                    toast.Show();
                }
            }
        }
        #endregion

        #region add favorite home
        HomeObject temHomeObject;
        private void Home_item_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            temHomeObject = (sender as Grid).DataContext as HomeObject;

            Grid item = sender as Grid;

            ContextMenu contextMenu = new ContextMenu();

            MenuItem addVideoFavorite = new MenuItem();
            addVideoFavorite.Header = "Add to favorite";
            addVideoFavorite.Click += addVideoFavorite_Click;

            MenuItem download = new MenuItem();
            download.Header = "Download";
            download.Click += download_Click;

            contextMenu.Items.Add(addVideoFavorite);
            contextMenu.Items.Add(download);
            ContextMenuService.SetContextMenu(item, contextMenu);
            contextMenu.IsOpen = true;
        }

        void download_Click(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.OpenReadCompleted += (s, ee) =>
            {
                App.PicToIsoStore(ee.Result, temHomeObject.Name+".jpg");
            };
            client.OpenReadAsync(new Uri(temHomeObject.Image, UriKind.Absolute));

            LocalVideo localvideo = new LocalVideo { 
                Id = temHomeObject.Name,
                Name = temHomeObject.Name,
                Img = temHomeObject.Name+".jpg",
                Url = temHomeObject.Link,
                Playlist = App.ViewModel.PlaylistList[0],
                Key = temHomeObject.Name  
            };
            
            App.ViewModel.AddVideo(localvideo);
            DownloadingPage.Download(localvideo);
            var toast = GetToastWithImgAndTitle(localvideo.Name+" has starting download", "");
            toast.TextWrapping = TextWrapping.Wrap;
            toast.Show();
        }

        void addVideoFavorite_Click(object sender, RoutedEventArgs e)
        {
            IList<DataFavorite> listData = null;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataFavorite> dataQuery = from data in readAndWriteDB.TableFavorite where data.name.Equals(temHomeObject.Name) && data.link.Equals(temHomeObject.Link) select data;
                listData = dataQuery.ToList();
                if (listData.Count > 0)
                {
                    var toast = GetToastWithImgAndTitle(temHomeObject.Name +App.message_exist, "");
                    toast.TextWrapping = TextWrapping.Wrap;
                    toast.Show();
                }
                else
                {
                    DataFavorite newsdata = new DataFavorite
                    {
                        ID = DateTime.Now.ToString(),
                        style = "0",
                        name = temHomeObject.Name,
                        type = temHomeObject.Type,
                        link = temHomeObject.Link,
                        image = temHomeObject.Image,
                        action = "",
                        imagevideo = ""
                    };
                    readAndWriteDB.TableFavorite.InsertOnSubmit(newsdata);
                    readAndWriteDB.SubmitChanges();
                    var toast = GetToastWithImgAndTitle(temHomeObject.Name + App.message_added, "");
                    toast.TextWrapping = TextWrapping.Wrap;
                    toast.Show();
                }
            }
        }
        #endregion

        #region favorite
        private void List_Favorite_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Favorite.SelectedIndex < 0)
                return;
            DataFavorite data = List_Favorite.SelectedItem as DataFavorite;
            if(data.style == "0")
            {
                App.URL = data.link;
                int type = int.Parse(data.type);
                switch (type)
                {
                    case 0:
                        {
                            NavigationService.Navigate(new Uri("/ViewVideoPage.xaml", UriKind.Relative));
                        } break;
                    case 1:
                        {

                        } break;
                    default: break;
                }
            }
            else
            {
                string CategoryName = data.name;
                CategoryName = CategoryName.Replace("&", "%26");
                App.CategoryAction = data.action;
                if (data.imagevideo == "1")
                    NavigationService.Navigate(new Uri("/CategoryDetailPage.xaml?name=" + CategoryName, UriKind.Relative));
                else
                    NavigationService.Navigate(new Uri("/CategoryDetailPage2.xaml?name=" + CategoryName, UriKind.Relative));
            }
        }
        string tempDataFavorite;
        private void Favorite_item_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            tempDataFavorite = ((sender as Grid).DataContext as DataFavorite).ID;
            Grid item = sender as Grid;

            ContextMenu contextMenu = new ContextMenu();
            MenuItem removeFavorite = new MenuItem();
            removeFavorite.Header = "Remove in favorite";
            removeFavorite.Click += removeFavorite_Click;

            contextMenu.Items.Add(removeFavorite);
            ContextMenuService.SetContextMenu(item, contextMenu);
            contextMenu.IsOpen = true;
        }

        void removeFavorite_Click(object sender, RoutedEventArgs e)
        {
            IList<DataFavorite> listData = null;
            string _name = "";
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataFavorite> dataQuery;
                dataQuery = from data in readAndWriteDB.TableFavorite where data.ID.Equals(tempDataFavorite) select data;
                listData = dataQuery.ToList();
                _name = listData[0].name;
                readAndWriteDB.TableFavorite.DeleteOnSubmit(listData[0]);
                readAndWriteDB.SubmitChanges();
                dataQuery = from data in readAndWriteDB.TableFavorite select data;
                listData = dataQuery.ToList();
                List_Favorite.DataContext = listData;
                var toast = GetToastWithImgAndTitle(_name + App.message_removed, "");
                toast.TextWrapping = TextWrapping.Wrap;
                toast.Show();
            }
        }
        #endregion

        private static ToastPrompt GetToastWithImgAndTitle(string _title, string _content)
        {
            return new ToastPrompt
            {
                Title = _title,
                TextOrientation = System.Windows.Controls.Orientation.Vertical,
                Message = _content
            };
        }

        #region downloaded
        private void List_Downloaded_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Downloaded.SelectedIndex < 0)
                return;
            App.URL = (List_Downloaded.SelectedItem as DownObject).D_Link;
            NavigationService.Navigate(new Uri("/ViewVideoPage.xaml?type=local", UriKind.Relative));
        }

        private void Downloaded_item_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }
        #endregion

        private void ItemDownloading_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ItemDownloading.SelectedIndex < 0)
                return;
            NavigationService.Navigate(new Uri("/DownloadingPage.xaml", UriKind.Relative));
        }
    }

}